#include <stdio.h>
#include <errno.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>

int main(int argc, char* argv[]) {
	char* buff;
	buff = malloc(1024);
	char* token;
	int status = 0;
	int length;
	char cwd[1024];
	char* copy;
	copy = malloc(1024);
	char* pass;
	pass = malloc(1024);
	char* path;
	path = malloc(1024);
	int pid;
	path = getenv("PATH"); //gets the path environment variable
	
	while(1) {
		printf("%% ");
		scanf("%[^\n]%*c", buff);
		length = strlen(buff);
		
		if(strcmp(buff, "dir") == 0) { //displays current working directory
			getcwd(cwd, sizeof(cwd));
			fprintf(stdout, "Current working dir: %s\n", cwd);
		}
		
		if(strcmp(buff, "exit") == 0) {
			exit(0);
		}
		//---------------------------------------------------------displays path
		else if(strcmp(buff, "path") == 0) {
			printf("%s\n", path);
		}
		//---------------------------------------------------------begin change directory
		else if(length > 4) {
			token = strtok(buff, " "); //gets first token of the string, puts it in token
			if(strcmp(token, "cd") == 0) {
				while(token != NULL) {
					token = strtok(NULL, " ");
					if(token != NULL) {
						strcat(pass, token); //puts remaining part of string after cd into pass var
					}
				}
				printf("This will change the directory.\n");
				if(chdir(pass) == -1) { //changes the directory
					printf("chdir error\n");
				}
				else {
					printf("Directory changed: \n");
					if (getcwd(cwd, sizeof(cwd)) != NULL) {
						fprintf(stdout, "Current working dir: %s\n", cwd);
						strcpy(pass,""); //empty the passing string
					}
					else {
						perror("getcwd() error");
					}
				}
			}
		//----------------------------------------------------------end change directory	
		//----------------------------------------------------------begin path append/remove
			else if(strcmp(token, "path") == 0) {
				//check for plus or minus sign; will be space, + or -, space, then pathname
				token = strtok(NULL, " "); // gets the next token, either + or -
				if(strcmp(token, "+") == 0) {
					token = strtok(NULL, " ");
					printf("For +, the token is %s\n", token);
				}
				else if (strcmp(token, "-") == 0) {
					token = strtok(NULL, " ");	
					printf("For -, the token is %s\n", token);
				}
			}
			
			//else if() { //todo; for pipes?
				
			//}
			
			else {
				printf("Command undefined.\n");
			}
		}
		
		else {
			printf("Command undefined.\n");
		}

	} //end while
	
	exit(0);
} //end main